<template>
    <div class="content">
        <div class="form_box">
            <el-form :model="requires" :rules="requires_rules" label-position="left" ref="requires" label-width="125px">
                <div class="form_width">
                    <h3 class="h3">发起监测需求</h3>
                    <el-form-item label="监测作品名称" prop="product_name">
                        <el-input v-model="requires.product_name" placeholder="" style="width:480px;"></el-input>
                    </el-form-item>
                    <!-- <el-form-item label="作品正版链接：" prop="product_url"> -->
                    <el-form-item
                        v-for="(domain, index) in requires.product_url"
                        :label="'作品正版链接' +(index+1)"
                        :key="domain.key"
                        :prop="'product_url.' + index + '.value'"
                        :rules="[
                            { validator: validateAuthUrl, trigger: 'blur'}
                        ]"
                    >
                        <el-input v-model="domain.value" placeholder="请以 http:// 或 https:// 开头" style="width:480px;">
                            <el-select class="product_url_select" v-model="domain.type" slot="append" placeholder="请选择">
                                <el-option label="网络链接" :value="1"></el-option>
                                <el-option label="网盘链接" :value="2"></el-option>
                            </el-select>
                        </el-input>
                        <el-button-group>
                            <el-button class="product_url_del" :disabled="(index == 0 && requires.product_url.length==1) ? true:false" @click.prevent="removeAuthUrl(domain)">删除</el-button>
                            <el-button class="product_url_add" v-if="index == requires.product_url.length-1"  @click="addAuthUrl">添加</el-button>
                        </el-button-group>
                    </el-form-item>
                    <el-form-item label="作品著作权人" prop="product_rightowner">
                        <el-input v-model="requires.product_rightowner" placeholder="" style="width:480px;">
                            <el-select class="product_url_select" v-model="requires.product_ownertype" slot="append" placeholder="请选择">
                                <el-option label="公司名称" :value="1"></el-option>
                                <el-option label="个人名称" :value="2"></el-option>
                            </el-select>
                        </el-input>
                    </el-form-item>
                    <el-form-item label="作品类型" prop="product_type">
                        <el-radio-group v-model="requires.product_type">
                            <el-radio v-for="item in product_type" :label="item.value" :key="item.label">{{ item.label }}</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="作品正版样本" prop="product_simple">
                        <el-upload class="upload-demo"
                        :action="uploadUrl"
                        :data="fileInfo.require_zhengbanyangpin"
                        :on-success="require_zhengbanyangpinSuccess"
                        :on-remove="require_zhengbanyangpinRemove"
                        :before-upload="require_zhengbanyangpinUpload"
                        :limit="5"
                        :on-exceed="require_zhengbanyangpinExceed"
                        :file-list="fileList.product_simple">
                            <el-button size="small" type="primary">点击上传</el-button>
                            <div slot="tip" class="el-upload__tip">最多上传5个文件，每个文件小于10M</div>
                        </el-upload>
                    </el-form-item>
                    
                    <el-form-item label="选择监测周期" prop="period">
                        <el-radio-group v-model="requires.period">
                            <el-radio v-for="item in period" :label="item.value" :key="item.label">{{ item.label }}</el-radio>
                        </el-radio-group>
                        <div class="el-upload__tip">监测开始时间自服务合同签署后第二日开始监测。</div>
                    </el-form-item>
                    <div class="contract">
                        <a :href="`${fileUrl}/cam/public/static/contract_service.docx`" download="中云文化大数据科技有限公司版权监测服务合同.docx">《中云文化大数据科技有限公司版权监测服务合同》</a>
                        <a :href="`${fileUrl}/cam/public/static/contract_entrust.docx`" download="中云文化大数据科技有限公司版权监测委托协议.docx">《中云文化大数据科技有限公司版权监测委托协议》</a>
                    </div>
                </div>
            </el-form>
            
            <div class="form_next">
                <el-button type="primary" @click="requiresAddFn">提交</el-button>
            </div>
        </div>
    </div>
</template>
<script>
import util from "@/assets/js/util.js"; // 时间格式化
import { submitfile,requiresAdd,host } from '@/api';
import { mapState, mapMutations } from "vuex";
function formatData(data) {
    var result = [];
    for (var key in data) {
        result.push({
            value: key
        });
    }
    return result;
}
export default {
    data() {
        return {
            // btnVisible: true,
            // 上传地址
            fileUrl: host,
            uploadUrl: submitfile,
            pic_length: 0,
            fileInfo: {
                require_zhengbanyangpin: {
                    type: "pic",
                    foler: "require_zhengbanyangpin"
                }
            },
            fileList: {
                product_simple: [],
            },
            requires: {
                product_name: '', // 作品名称
                product_rightowner: '', // 著作权人
                product_ownertype: 1, // 著作权人类型
                product_url: [ // 正版链接
                    {
                        value: '',
                        type: 1, // 正版链接类型
                    }
                ],
                product_type: '', // 作品类型
                product_simple: [], // 正版样本
                period: '', // 监测周期
            },
            requires_rules: {
                product_name: [{ required: true, message: "请填写监测作品名称" }], // 作品名称
                product_rightowner: [{ required: true, message: "请填写作品著作权人" }], // 著作权人
                product_type: [{ required: true, message: "请选择作品类型" }], // 作品类型
                product_simple: [{ required: true, message: "请上传正版样本" }], // 正版样本
                period: [{ required: true, message: "请选择监测周期" }]
            },

            // 作品类型选项
            product_type: [
                {
                    value: 1,
                    label: "文字"
                },
                {
                    value: 2,
                    label: "视频"
                },
                {
                    value: 3,
                    label: "图片"
                },
                {
                    value: 4,
                    label: "音乐"
                }
            ],
            period: [
                {
                    value: 1,
                    label: "一个月"
                },
                {
                    value: 2,
                    label: "三个月"
                },
                {
                    value: 3,
                    label: "半年期"
                },
                {
                    value: 4,
                    label: "一年期"
                }
            ],

            pickerOptions: {
                shortcuts: [
                    {
                        text: "最近一周",
                        onClick(picker) {
                            const end = new Date();
                            const start = new Date();
                            start.setTime(
                                start.getTime() - 3600 * 1000 * 24 * 7
                            );
                            picker.$emit("pick", [start, end]);
                        }
                    },
                    {
                        text: "最近一个月",
                        onClick(picker) {
                            const end = new Date();
                            const start = new Date();
                            start.setTime(
                                start.getTime() - 3600 * 1000 * 24 * 30
                            );
                            picker.$emit("pick", [start, end]);
                        }
                    },
                    {
                        text: "最近三个月",
                        onClick(picker) {
                            const end = new Date();
                            const start = new Date();
                            start.setTime(
                                start.getTime() - 3600 * 1000 * 24 * 90
                            );
                            picker.$emit("pick", [start, end]);
                        }
                    }
                ]
            }
        };
    },
    computed: {
        ...mapState([
            'croUser',
        ]),
    },
    methods: {
        ...mapMutations([
            'OUT_LOGIN',
        ]),
    
        // 作品正版样本：
        require_zhengbanyangpinRemove(file, fileList) {
            if(this.pic_length==0) return;
            this.pic_length--
            this.requires.product_simple.remove(file.response.data);
        },
        require_zhengbanyangpinSuccess(res, file) {
            this.pic_length++
            this.requires.product_simple.push(res.data);
            console.log(this.pic_length,this.requires.product_simple.length,'++');
        },
        require_zhengbanyangpinUpload(file) {
            // const isJPG = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'application/pdf';
            const isLt2M = file.size / 1024 / 1024 < 10;
            // if (!isJPG) {
            //     this.$message.error('上传正版样本只能是 JPEG/PNG/PDF 格式!');
            // }
            if (!isLt2M) {
                this.$message.error('上传正版样本大小不能超过 10MB!');
            }
            return isLt2M;
        },
        require_zhengbanyangpinExceed(files, fileList) {
            this.$message.warning(`最多上传5个文件`);
        },

        dateChange(val) {
            // 2017-10-03 - 2017-10-04
            this.requires.start_time = val[0] = !val[0] || val[0] == "" ? "" : util.formatDate.format(new Date(val[0]), "yyyy-MM-dd");
            this.requires.end_time = val[1] = !val[1] || val[1] == "" ? "" : util.formatDate.format(new Date(val[1]), "yyyy-MM-dd");
            console.log(this.requires);
        },
        requiresAddFn() {
            this.$refs.requires.validate(valid => {
                if (valid) {
                    const loading = this.$loading({
                        lock: true,
                        text: '正在上传',
                        spinner: 'el-icon-loading',
                        background: 'rgba(0, 0, 0, 0.7)'
                    });

                    // 图片上传
                    let _this = this;
                    let timer1= setInterval(()=>{
                        if(_this.pic_length === _this.requires.product_simple.length){
                            // 清除定时器
                            clearInterval(timer1); 
                            clearTimeout(timer2);
                            timer1 = null; 
                            timer2 = null;

                            async function submit() {
                                let para = Object.assign({}, _this.requires);
                                para.user_id = _this.croUser.user_id;
                                let purl_arr= para.product_url;
                                let product_url = [];
                                for(let i=0;i<purl_arr.length;i++){
                                    product_url[i] = `${purl_arr[i].type},${purl_arr[i].value}`;
                                }
                                para.product_url = product_url;
                                let res_add  = await requiresAdd(para);
                                if(res_add.data){
                                    _this.$refs.requires.resetFields();
                                    _this.pic_length = 0;
                                    _this.requires.product_url=[{value:'',type:'1'}];
                                    _this.fileList = {
                                        product_simple: [] // 样本
                                    };
                                    _this.$message.success(res_add.msg);
                                }else if(res_add.tologin) {
                                    _this.OUT_LOGIN();
                                    _this.$router.push('/login');
                                }else {
                                    _this.$message.error(res_add.msg);
                                }

                                loading.close();
                            }
                            submit();
                        }
                    },30);
                    // 请求超时
                    let timer2 = setTimeout(()=>{
                        // 清除定时器
                        clearInterval(timer1); 
                        clearTimeout(timer2);
                        timer1 = null; 
                        timer2 = null;
                        this.$message('请求超时，请重试');
                        loading.close();
                    },5000);
                }
            });
        },
        // 判断是否为IP地址
        isIp(value){
            let regexp = /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/;

            let valid = regexp.test(value);
    
            if(!valid){//首先必须是 xxx.xxx.xxx.xxx 类型的数字，如果不是，返回false
                return false;
            }
            
            return value.split('.').every(function(num){
                //切割开来，每个都做对比，可以为0，可以小于等于255，但是不可以0开头的俩位数
                //只要有一个不符合就返回false
                if(num.length > 1 && num.charAt(0) === '0'){
                    //大于1位的，开头都不可以是‘0’
                    return false;
                }else if(parseInt(num , 10) > 255){
                    //大于255的不能通过
                    return false;
                }
                return true;
            });
        },
        IsURL(str_url) {            	
            return !!str_url.match(/^(http|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?/);
        },
        //验证授权网址
        validateAuthUrl: function(rule, value, callback){
            if (value === '') {
                callback();
            } else {
                let domainArr = value.match(/[\w-]+\.(com|net|org|gov|cc|biz|info|cn|co|mobi|name|sh|ac|la|travel|tm|us|cc|tv|jobs|asia|hn|lc|hk|bz|ws|tel|io|tw|is|edu|mil|au|jp|int|kr|de|vc|ag|in|me|gd|vg|be|sg|it|ro|pw|win|cm|im|ca|top|wang|tt|so|xyz|vip|tn)\b(\.(cn|hk|uk|jp|tw|kr|mo|kr|ru))*/);
                // 2017-11-14 18:00:31 liuzz
                if(!domainArr){
                    let urlReg = /[a-zA-Z0-9][-a-zA-Z0-9]{0,62}(\.[a-zA-Z0-9][-a-zA-Z0-9]{0,62})+\.?/;  
                    let urlIP=urlReg.exec(value);
                    if(urlIP){
                        if(this.isIp(urlIP[0])){
                            domainArr = true;
                        }
                    }
                }
                if(!this.IsURL(value) || !domainArr){
                    callback(new Error('此网址不是以http://https://开头，或者不是网址'));
                }else{
                    callback();
                }
            }
        },  
        removeAuthUrl(item) {
            var index = this.requires.product_url.indexOf(item)
            if (index !== -1) {
                this.requires.product_url.splice(index, 1)
            }
        },
        addAuthUrl() {
            this.requires.product_url.push({
                value: '',
                type: 1,
                key: Date.now()
            });
        },
    },
    mounted() {
    }
};
</script>
<style lang="scss" scoped>
.content {
    width: 100%;
    margin: 0 auto;
    box-sizing: border-box;
    padding: 15px 0;
    background: #f2f2f2;
    font-size: 14px;
}

.form_box {
    border: 1px solid #e9e9e9;
    width: 1200px;
    margin: 0 auto;
    background: #fff;
}

.form_box .h3 {
    font-size: 22px;
    // font-weight:700;
    padding: 30px 0;
    text-align: center;
}

.el-checkbox-group .el-checkbox {
    padding: 0px 15px 0px 0;
}

.el-radio-group .el-radio {
    padding-right: 15px;
    line-height: 36px;
}

.el-checkbox + .el-checkbox,
.el-radio + .el-radio {
    margin: 0;
}

.form_next {
    text-align: center;
    padding-bottom: 30px;
}

.form_width {
    width: 830px;
    margin: 0 auto;
    padding-left: 80px;
}
.product_url_select {
    width: 110px;
}
.el-upload__tip {
    line-height: 1;
}
.contract {
    text-align: center;
    padding-bottom: 22px;
    line-height: 40px;
    a {
        color:#2c8bd1;
    }
}
</style>
